﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DMS.Base;
using DMS.BaseClass;
using DMS.Business.Modules.Organization;
using DMS.Business.Utility;
using DMS.Data;
using DMS.Data.Modules.ArchivesManagement;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DMS.Business.Modules.ArchivesManagement
{
    public class ZHArchInfoService
    {
        public static AM_BaseInfo GetBaseInfoById(string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                return db.AM_BaseInfo.Where(p => p.BaseInfoID == baseInfoId).FirstOrDefault();
            }
        }

        /// <summary>
        /// 查询基本信息
        /// </summary>
        /// <param name="actor">参与者，如果为空则不过滤权限</param>
        /// <param name="condition1">条件1</param>
        /// <param name="condition2">条件2</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页条数，如果小于等于0，则返回所有</param>
        /// <param name="total">总数</param>
        /// <returns></returns>
        public static List<ZHArchInfo> GetZHArchInfos(User actor, string condition1,string condition2, int pageIndex, int pageSize,
                                                     out int total)
        {
            using (var db = new DMSEntities())
            {
                //权限过滤
                condition1 += GetLimitCondition(actor);

                int skinCount = (pageIndex - 1)*pageSize;

                //var q = db.ExecuteStoreQuery<ZHArchInfo>(string.Format(query1,condition));
                var baseInfos = db.AM_BaseInfo.Where(" it.IsDeleted=false and it.Type = 'ZH' " + condition1);
                var archInfos = db.AM_ArchivesInfo.Where(" 1=1 "+ condition2).Join(baseInfos, archInfo => archInfo.BaseInfoID,
                                                        baseInfo => baseInfo.BaseInfoID,
                                                        (archInfo, baseInfo) => new ZHArchInfo
                                                                                    {
                                                                                        ArchivesID = archInfo.ArchivesID,
                                                                                        BaseInfoID = archInfo.BaseInfoID,
                                                                                        Name = archInfo.Name,
                                                                                        Type = archInfo.Type,
                                                                                        BelongYear = archInfo.BelongYear,
                                                                                        //BelongMonth =
                                                                                        //    archInfo.BelongMonth,
                                                                                        InitDate = archInfo.InitDate,
                                                                                        CustodyBeginDate =
                                                                                            archInfo.CustodyBeginDate,
                                                                                        CustodyYear =
                                                                                            archInfo.CustodyYear,
                                                                                        CustodyEndDate =
                                                                                            archInfo.CustodyEndDate,
                                                                                        PersonName = archInfo.PersonName,
                                                                                        PageCount = archInfo.PageCount,
                                                                                        InputPersonID =
                                                                                            archInfo.InputPersonID,
                                                                                        InputPersonName =
                                                                                            archInfo.InputPersonName,
                                                                                        InputDate = archInfo.InputDate,
                                                                                        Remark = archInfo.Remark,
                                                                                        Supplement = archInfo.Supplement,
                                                                                        IsDestroy = archInfo.IsDestroy,
                                                                                        IsDeleted = archInfo.IsDeleted,
                                                                                        BoxCode = baseInfo.BoxCode,
                                                                                        BoxPosition =
                                                                                            baseInfo.BoxPosition
                                                                                    }).OrderByDescending(p=>p.InitDate);

                total = archInfos.Count();

                if (skinCount > total && pageSize > 0)
                {
                    skinCount = total - (total%pageSize);
                }

                List<ZHArchInfo> list;
                if (pageSize > 0)
                    list = archInfos.Skip(skinCount).Take(pageSize).ToList();
                else
                    list = archInfos.ToList();

                return list;
            }
        }

        /// <summary>
        /// 获取权限过滤条件
        /// </summary>
        /// <returns></returns>
        private static string GetLimitCondition(User actor)
        {
            string condition = "";

            if (actor == null)
                return "";

            if (actor.IsInRole("系统管理员;县局管理员"))
                return "";
            {
                condition += string.Format(" and it.DeptID='{0}'", actor.BigDept.ID);
            }

            return condition;
        }

        public static void SaveOrUpdateBaseInfo(AM_BaseInfo baseInfo)
        {
            using (var db = new DMSEntities())
            {
                var tBaseInfo = db.AM_BaseInfo.FirstOrDefault(p => p.BaseInfoID == baseInfo.BaseInfoID);
                if (tBaseInfo != null) //更新
                {
                    db.ApplyCurrentValues("AM_BaseInfo", baseInfo);
                }
                else //新增
                {
                    baseInfo.IsDeleted = false;
                    db.AM_BaseInfo.AddObject(baseInfo);
                }
                db.SaveChanges();
            }
        }

        public static void SaveBaseInfoList(List<AM_BaseInfo> baseInfoList)
        {
            using (var db = new DMSEntities())
            {
                foreach(var baseInfo in baseInfoList)
                {
                    db.AM_BaseInfo.AddObject(baseInfo);
                }
                db.SaveChanges();
            }
        }

        public static void DeleteBaseInfo(string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var baseInfo = db.AM_BaseInfo.Where(p => p.BaseInfoID == baseInfoId).FirstOrDefault();
                if (baseInfo != null)
                {
                    baseInfo.IsDeleted = true;
                    db.SaveChanges();
                }
            }
        }

        public static bool IsUnitNameExist(string unitName,string type,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.UnitName == unitName && p.Type == type && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static bool IsTaxCodeExist(string taxCode,string type,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.TaxCode == taxCode && p.Type == type && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static bool IsInsuranceCodeExist(string insuranceCode,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.TaxCode == insuranceCode && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static List<DataTable> GetZHArchInfoTable(User actor, string condition1,string condition2)
        {
            int total;
            var list = GetZHArchInfos(actor, condition1,condition2, 0, -1, out total);

            if (list.Count > 65535)
                return null;

            List<DataTable> tables = new List<DataTable>();

            #region 表头初始化

            DataTable dt = new DataTable();
            dt.TableName = "综合资料信息";
            dt.Columns.Add("档案盒编号");
            dt.Columns.Add("档案盒所在位置");
            dt.Columns.Add("档案名称");
            dt.Columns.Add("所属年度");
            dt.Columns.Add("档案形成日期");
            dt.Columns.Add("保管起始日期");
            dt.Columns.Add("档案保管年限");
            dt.Columns.Add("到期日期");
            dt.Columns.Add("张数");
            dt.Columns.Add("是否销毁");
            dt.Columns.Add("备注");
            dt.Columns.Add("补充说明");
            dt.Columns.Add("档案录入人员");
            dt.Columns.Add("档案录入日期");

            DataRow dr1 = dt.NewRow();

            dr1["档案盒编号"] = "档案盒编号";
            dr1["档案盒所在位置"] = "档案盒所在位置";
            dr1["档案名称"] = "档案名称";
            dr1["所属年度"] = "所属年度";
            dr1["档案形成日期"] = "档案形成日期";
            dr1["保管起始日期"] = "保管起始日期";
            dr1["档案保管年限"] = "档案保管年限";
            dr1["到期日期"] = "到期日期";
            dr1["张数"] = "张数";
            dr1["是否销毁"] = "是否销毁";
            dr1["备注"] = "备注";
            dr1["补充说明"] = "补充说明";
            dr1["档案录入人员"] = "档案录入人员";
            dr1["档案录入日期"] = "档案录入日期";
            dt.Rows.Add(dr1);

            #endregion

            foreach (var exportRow in list)
            {
                DataRow dr = dt.NewRow();
                dr["档案盒编号"] = exportRow.BoxCode;
                dr["档案盒所在位置"] = exportRow.BoxPosition;
                dr["档案名称"] = exportRow.Name;
                dr["所属年度"] = exportRow.BelongYear;
                dr["档案形成日期"] = exportRow.InitDate.HasValue?exportRow.InitDate.Value.ToShortDateString():"";
                dr["保管起始日期"] = exportRow.CustodyBeginDate.HasValue?exportRow.CustodyBeginDate.Value.ToShortDateString():"";
                dr["档案保管年限"] = (exportRow.CustodyYear.HasValue && exportRow.CustodyYear.Value == 0)
                                   ? "永久"
                                   : (exportRow.CustodyYear??0).ToString();
                dr["到期日期"] = exportRow.CustodyEndDate.HasValue?exportRow.CustodyEndDate.Value.ToShortDateString():"";
                dr["张数"] = exportRow.PageCount;
                dr["是否销毁"] = exportRow.IsDestroy??false?"是":"否";
                dr["备注"] = exportRow.Remark;
                dr["补充说明"] = exportRow.Supplement;
                dr["档案录入人员"] = exportRow.InputPersonName;
                dr["档案录入日期"] = exportRow.InputDate;
                dt.Rows.Add(dr);
            }
            tables.Add(dt);
            return tables;
        }
    }
}
